<?php
/**
 * * get stats by partner id
 *
 * @author     ben
 */
class getStatsChartDataAction extends WacStatsAction
{
    public $output;
    public $partner;
    public $sites;
    public $periods;
    public $statsResult;

    

    public function execute($request)
    {
        sfConfig::set('sf_web_debug', false);
        $this->setLayout(false);
//        $periods = $this->getPeriods($request);
//        $swfParams = $this->prepareParams($request);
//        $this->output = print_r($swfParams, true);

//        return $this->_outputSWF($request, $swfParams);
        return $this->_outputBar3DSWFTest($request);

//        return $this->renderText($this->output);
    }

    /*
     * prepare swf file params
     * @return array
     */
    public function prepareParams($request)
    {
        $dateTimeCalculator = new DateTimeCalculator(date("Y-m-d"), "Y-m-d");
//        $user = $this->context->getUser();
        $startDate = $request->getParameter("start_year").'-'.$request->getParameter("start_month").'-'.($request->getParameter("start_day"));
        $startDate = strftime("%Y-%m-%d",strtotime($startDate));
        $endDate = $request->getParameter("end_year").'-'.$request->getParameter("end_month").'-'.($request->getParameter("end_day"));
        $endDate = strftime("%Y-%m-%d",strtotime($endDate));
        $periodDays = $dateTimeCalculator->calculate_two_dates($startDate, $endDate);

        // bcz the date calculate rule is >= startdate and < endate, so fix the enddate
        $dateTimeCalculator->set_date_time($endDate, "Y-m-d");
        $endDate = $dateTimeCalculator->calculate('day', 1, 'add', true);

        $dateTimeCalculator->set_date_time($startDate, "Y-m-d");
        $prePeriodEndDate = $startDate;

        $dateTimeCalculator->set_date_time($prePeriodEndDate, "Y-m-d");
        $prePeriodStartDate = $dateTimeCalculator->calculate('day', $periodDays, 'sub', true);
        
//echo "ffffffffff:{$startDate}, {$endDate}, $periodDays";
//echo "ffffffffff:{$prePeriodStartDate}, {$prePeriodEndDate}";
        $partnerId = $request->getParameter('partner_id');
        $params = array();

        if(!empty($partnerId))
        {
            if($partnerId == 'all')
            {
                $this->sites = Doctrine::getTable('Site')->findAll();
            }
            else
            {
                $this->partner = Doctrine::getTable('Partner')->findOneById($partnerId);
                $this->sites = Doctrine::getTable('Site')->findByPartnerId($this->partner->getId());
            }

            $statsGlobalTable = Doctrine::getTable('StatsGlobal');            
            $param = array('site_id'=>'', 'site_name'=>'', 
                           'period_days'=>$periodDays, 'start_date'=>$startDate, 'end_date'=>$endDate,
                           'pre_period_start_date'=>$prePeriodStartDate, 'pre_period_end_date'=>$prePeriodEndDate,
                           'visitor_number'=>'', 'appraisal_number'=>'', 'client_number'=>'', 'vehicle_sale_number'=>'');

            $siteIds = array();
            if($this->sites->count()>0)
            {
                foreach($this->sites as $site)
                {
                    $siteIds = array($site->getId());
                    $rs = $statsGlobalTable->getStatsBySitesAndDate('all', $siteIds, $startDate, $endDate, true);
                    $prePeriodRs = $statsGlobalTable->getStatsBySitesAndDate('all', $siteIds, $prePeriodStartDate, $prePeriodEndDate, true);

                    $param['site_id']             = $site->getId();
                    $param['site_name']           = $site->getNameInUrl();
                    $param['visitor_number']      = empty($rs[0]['visitor_number']) ?   0:$rs[0]['visitor_number'];
                    $param['appraisal_number']    = empty($rs[0]['appraisal_number']) ? 0:$rs[0]['appraisal_number'];
                    $param['client_number']       = empty($rs[0]['client_number']) ?    0:$rs[0]['client_number'];
                    $param['vehicle_sale_number'] = empty($rs[0]['vehicle_sale_number']) ? 0:$rs[0]['vehicle_sale_number'];

                    $param['pre_period_visitor_number']      = empty($prePeriodRs[0]['visitor_number']) ?   0:$prePeriodRs[0]['visitor_number'];
                    $param['pre_period_appraisal_number']    = empty($prePeriodRs[0]['appraisal_number']) ? 0:$prePeriodRs[0]['appraisal_number'];
                    $param['pre_period_client_number']       = empty($prePeriodRs[0]['client_number']) ?    0:$prePeriodRs[0]['client_number'];
                    $param['pre_period_vehicle_sale_number'] = empty($prePeriodRs[0]['vehicle_sale_number']) ? 0:$prePeriodRs[0]['vehicle_sale_number'];

                    if($param['pre_period_vehicle_sale_number']!=0)
                    {
                        $param['comparison_percent'] = ($param['vehicle_sale_number'] - $param['pre_period_vehicle_sale_number']) / $param['pre_period_vehicle_sale_number'];
                        $param['comparison_percent'] = round($param['comparison_percent'], 2) * 100;
                        $param['comparison_percent'] = $param['comparison_percent'].'%';
                        $param['comparison_percent'] = ($param['vehicle_sale_number'] - $param['pre_period_vehicle_sale_number'])>0 ? "+{$param['comparison_percent']}" : "-{$param['comparison_percent']}";
                    }
                    else
                    {
                        $param['comparison_percent']= "N/A";
                    }
//                    
                    $params[] = $param;
                }
            }

            $sortParams = array_values(SortUtility::arrayNatsortList($params, true, "client_number"));
        }
        return $sortParams;
    }


    protected function _outputSWF($request, $swfParams)
    {
        $chartData = array();
        
        $swfParamsCount = count($swfParams);
        if($swfParamsCount==0)
        {
            return sfView::NONE;
        }

         //Create new stBar3D object and set the transparency and colour.
		$redBar = new stBar3D( 75, '#d01f3c' );
		$redBar->key( 'Visites', 10 );

		//2nd Bar
		$blueBar = new stBar3D( 75, '#356aa0' );
		$blueBar->key( 'Leads', 10 );

        //3nd Bar
		$greenBar = new stBar3D( 75, '#80FF00' );
		$greenBar->key( 'Ventes', 10 );

        //assign data
        $maxNumber = 0;
        for( $i = 0; $i < $swfParamsCount; $i++ )
        {
            $redBar->data[]   = $swfParams[$i]['visitor_number'];
            $maxNumber = ($swfParams[$i]['visitor_number']>$maxNumber) ? $swfParams[$i]['visitor_number'] : $maxNumber;

            $blueBar->data[]  = $swfParams[$i]['client_number'];
            $maxNumber = ($swfParams[$i]['client_number']>$maxNumber) ? $swfParams[$i]['client_number'] : $maxNumber;
            
            $greenBar->data[] = $swfParams[$i]['vehicle_sale_number'];
            $maxNumber = ($swfParams[$i]['vehicle_sale_number']>$maxNumber) ? $swfParams[$i]['vehicle_sale_number'] : $maxNumber;

            $chartXLabels[]   = $swfParams[$i]['site_name']."\n ".$swfParams[$i]['comparison_percent'];
        }
        $maxHigh = $maxNumber + (10 - $maxNumber%10);

        if($maxHigh<= 100)
        {
            $step =4;
        }
        else
        {
            $step =8 ;
        }


		$g = new stGraph();
		$g->bg_colour = '#E4F5FC';
		$g->title( 'Statistiques partenaires', '{font-size:20px; color: #18A6FF;}' );

		$g->data_sets[] = $redBar;
		$g->data_sets[] = $blueBar;
                $g->data_sets[] = $greenBar;

		//to create 3d x-axis
		$g->set_x_axis_3d( 10 );
		$g->x_axis_colour( '#8499A4', '#E4F5FC' );
		$g->y_axis_colour( '#8499A4', '#E4F5FC' );

		$g->set_x_labels( $chartXLabels );
		$g->set_y_max( $maxHigh );
		$g->y_label_steps( $step );
		$g->set_y_legend( 'Nombre', 12, '#18A6FF' );
		echo $g->render();

		return sfView::NONE;
    }

    
}